﻿using QiuShiBaiKe.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiuShiBaiKe.DAL
{
    public class MessageDAL
    {
        private QiuShiBaiKe.Model.QiuShiBaiKeDBEntities entity;

        public MessageDAL(QiuShiBaiKe.Model.QiuShiBaiKeDBEntities entity)
        {
            this.entity = entity;
        }

        /// <summary>
        /// 根据主键获得糗事
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Message GetById(long id)
        {
            return entity.Messages.Where(u => u.Id == id).FirstOrDefault();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="msg"></param>
        /// <param name="isAnonymous"></param>
        /// <param name="imageUrl"></param>
        /// <returns>新增消息的id</returns>
        public long Add(long userId, string msg, bool isAnonymous, string imageUrl)
        {
            Message message = new Message();
            message.ImageUrl = imageUrl;
            message.IsAnonymous = isAnonymous;
            message.Msg = msg;
            message.UserId = userId;
            message.CreateDateTime = DateTime.Now;
            entity.Messages.Add(message);
            entity.SaveChanges();
            return message.Id;//保存后自动增长字段就会通过Id属性取到了
        }

        /// <summary>
        /// 获得第pageIndex页的数据，每一页显示pageSize条
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public Message[] GetMessages(int pageIndex, int pageSize)
        {
            return entity.Messages.OrderByDescending(u => u.CreateDateTime)
                    .Skip((pageIndex - 1) * pageSize).Take(pageSize)
                    .ToArray();            
        }

        /// <summary>
        /// 获得消息的总条数
        /// </summary>
        /// <returns></returns>
        public int GetMessagesCount()
        {
            return entity.Messages.Count();
        }
    }
}
